//聊天红点提醒（未读消息）
export const setRemind = data => {
    window.localStorage.setItem("remind", JSON.stringify(data));
}

//聊天红点提醒（未读消息）
export const getRemind = data => {
    return JSON.parse(window.localStorage.getItem("remind"));
}

//语音授权
export const setVoice = data => {
    window.localStorage.setItem("voice", JSON.stringify(data));
}

//语音授权
export const getVoice = data => {
    return JSON.parse(window.localStorage.getItem("voice"));
}

//头像
export const setProfile = data => {
    window.localStorage.setItem("profile", JSON.stringify(data));
}

//头像
export const getProfile = data => {
    return JSON.parse(window.localStorage.getItem("profile"));
}

//@功能
export const setAt = data => {
    window.localStorage.setItem("at", JSON.stringify(data));
}

//@功能
export const getAt = data => {
    return JSON.parse(window.localStorage.getItem("at"));
}

//删除群组
export const setDelgroup = data => {
    window.localStorage.setItem("del", JSON.stringify(data));
}

//删除群组
export const getDelgroup = data => {
    return JSON.parse(window.localStorage.getItem("del"));
}

//历史文件
export const setHistory = data => {
    window.localStorage.setItem("history", JSON.stringify(data));
}

//历史文件
export const getHistory = data => {
    return JSON.parse(window.localStorage.getItem("history"));
}

//是否包含
export const isInclude = (arr,value)=>{

}

//获取光标位置
export const getCursortPosition = element=>{
    var CaretPos = 0;
    if (document.selection) {//支持IE
        element.focus();
        var Sel = document.selection.createRange();
        Sel.moveStart('character', -element.value.length);
        CaretPos = Sel.text.length;
    }
    else if (element.selectionStart || element.selectionStart == '0')//支持firefox
        CaretPos = element.selectionStart;
    return (CaretPos);
}

//根据id查找下标
export const findIndex = (arr,key,word)=>{
	let t = '';
	arr.map((o,n)=>{
		if(o[key] == word){
			t = n;
		}
	})
	return t;
}

//清除红点
export const clearHot = (id)=>{
    let hots = getRemind();
    if(hots){
        hots.map((o,n)=>{
            if(o == id){
                hots.splice(n,1);
            }
        })
        setRemind(hots);
    }
}

//设置红点
export const setHot = (id)=>{
    console.log('开启红点');
	let groups = getRemind()?getRemind():[];
	groups.push(id);
	let arr = unique(groups); //去重
	setRemind(arr); //写入缓存
}

//数组去重
export const unique = arr =>{
    var result = [];
    for(var i = 0; i < arr.length; i++)
    {
        if (result.indexOf(arr[i]) == -1){
			result.push(arr[i]);
		}
    }
    return result;
}

//过滤消息
export const fileterMsg = obj =>{
	if(obj){
		if(obj.ext.type == 'text' || obj.ext.type == 'txt'){
			return obj.ext.content;
		}
		else if(obj.ext.type == 'image'){
			return '[图片]';
		}
		else if(obj.ext.type == 'map'){
			return '[位置]';
		}
		else if(obj.ext.type == 'editImg'){
			return '[图片]'
		}
        else if(obj.ext.type == 'editNone'){
            return '[图片]'
        }
		else if(obj.ext.type == 'works'){
			return '[作品]'
		}
        else if(obj.ext.type == 'voice'){
            return '[语音]'
        }
        else if(obj.ext.type == 'remindOver'){
            return '[提醒结算收图]'
        }
        else if(obj.ext.type == 'remindTime'){
            return '[提醒修改时间]'
        }
        else if(obj.ext.type == 'remindUpload'){
            return '[提醒上传图片]'
        }
        else if(obj.ext.type == 'remindPay'){
            return '[提醒付款]'
        }
        else if(obj.ext.type == 'remindConfirm'){
            return '[提醒确认图片]'
        }
        else if(obj.ext.type == 'remindModif'){
            return '[提醒改图]'
        }
        else if(obj.ext.type == 'timerAgree'){
            return '[同意开启计时器]'
        }
        else if(obj.ext.type == 'timerStart'){
            return '[请求开始计时]'
        }
        else if(obj.ext.type == 'timerPause'){
            return '[已暂停计时]'
        }
        else if(obj.ext.type == 'timerFinish'){
            return '[已完成计时]'
        }
        else if(obj.ext.type == 'timerContinue'){
            return '[已继续计时]'
        }
        else if(obj.ext.type == 'timerModif'){
            return '[请求修改时间]'
        }
		else{
			return '[推送消息]';
		}
	}
}

//压缩图片
export const compressImage = path=>{
	return new Promise ((resolve, reject)=>{
		plus.zip.compressImage({
			src:path,  //原图片
			dst:'_doc/chat/gallery/' + path, //压缩后的图片
			overwrite:true,  //覆盖文件
			quality:50  //图片质量
		},r=>{
			resolve(r.target);
		},error=>{
			reject(null);
			console.log('压缩失败的回调');
		})
	})
}

//转base64
export const toBase64 = path=>{
	return new Promise ((resolve, reject)=>{
		plus.io.resolveLocalFileSystemURL(path, entry=> {
			entry.file(file=>{
				// 转base64
				var fileReader = new plus.io.FileReader();
				fileReader.readAsDataURL(file);
				fileReader.onload = e=> {
					resolve(e.target.result);
				}
			} );
		}, e=> {
			reject(e.message);
		});
	})
}

//图片转base64
export const getBase64Image = (url,callback) =>{
	console.log('开始转');
	var image = new Image();
	image.src = url;
	image.onload = function() {
		_getBase64Image(image);
	}
	let _getBase64Image = (img) => {
		var canvas = document.createElement("canvas");
		var width = img.width;
		var height = img.height;
		if (width > height) {
			if (width > 100) {
				height = Math.round(height *= 100 / width);
				width = 100;
			}
		} else {
			if (height > 100) {
				width = Math.round(width *= 100 / height);
				height = 100;
			}
		}
		canvas.width = width;   /*设置新的图片的宽度*/
		canvas.height = height; /*设置新的图片的长度*/
		var ctx = canvas.getContext("2d");
		ctx.drawImage(img, 0, 0, width, height); /*绘图*/
		var dataURL = canvas.toDataURL("image/png", 0.8);
		callback(dataURL.replace("data:image/png;base64,", ""));
	}
}

//时间戳转时间
function formatDate(date, fmt) {
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
    };
    for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
            let str = o[k] + '';
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
        }
    }
    return fmt;
}
function padLeftZero(str) {
    return ('00' + str).substr(str.length);
}
export function toDate(time,format){
	var date = new Date(time);
	return formatDate(date, format);
}
